/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.command;

import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.Viewport;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.commands.Command;

/**
 * Decided the initial size for an interaction. This command selects a size that
 * fits neatly inside the current viewport.
 * 
 * <p>
 * The following attributes must be set before the command can run successfully:
 * </p>
 * <ul>
 * <li>AnyEditPart
 * </ul>
 * 
 * <p>
 * When completed, the following attributes can be read to access the result:
 * </p>
 * <ul>
 * <li>PreferredBounds
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 */
public class DecideInteractionBoundsCommand extends Command {
	private GraphicalEditPart anyEditPart;
	private Rectangle bounds;

	/**
	 * Amount of space to leave between the viewport border and the interaction
	 * frame border.
	 */
	private static final int MARGIN = 15;

	public void setAnyEditPart(final GraphicalEditPart editpart) {
		this.anyEditPart = editpart;
	}

	public Rectangle getPreferredBounds() {
		return bounds;
	}

	@Override
	public void execute() {
		//Darpan
		IFigure figure = anyEditPart.getFigure();
		if (figure instanceof FreeformLayer) {
			while (!(figure instanceof Viewport))
				figure = figure.getParent();
			
			Viewport viewport = (Viewport) figure;
			int width = viewport.getHorizontalRangeModel().getExtent() - 2 * MARGIN;
			int height = viewport.getVerticalRangeModel().getExtent() - 2 * MARGIN;
			bounds = new Rectangle(MARGIN, MARGIN, width, height);
		} else if (figure instanceof RectangleFigure) {
			// This is using the AdaptedSequenceDiagramEditPart
			// from the posterboard implementation
			RectangleFigure rectangle = (RectangleFigure) figure;
			bounds = new Rectangle(MARGIN, 
					MARGIN, 
					rectangle.getSize().width - 2 * MARGIN, 
					rectangle.getSize().height - 2 * MARGIN);
		}
		//Darpan
		
	}

	@Override
	public void redo() {
		execute();
	}

	@Override
	public void dispose() {
		bounds = null;
		anyEditPart = null;
	}
}
